package com.highglass.videoplayer;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.TimedText;
import android.net.Uri;
import android.os.Message;
import android.os.SystemProperties;
import android.util.Log;

import com.highglass.videoplayer.uitl.LibSwitchHelper;
import com.playmodule.MediaUtil;

import java.io.File;
import java.io.IOException;

/**
 * Created by wangjianqiang on 2016/11/17.
 */
public class MediaHelper extends MediaUtil {
    public static int TEN_MINUTES = 0;
    public static int ONE_HOUR = 1;
    public static int END = 2;
    private int adverMode = 0;
    private Uri mUri;
    private Uri mAdverUri;
    private int mDuration = 0;
    private MediaPlayer mMediaPlayer = null;
    public boolean mIsPrepared;
    private int mCurrentBufferPercentage;
    private VideoPlayActivity mActivity;
    private AdverInterface adverInterface;

    private int mRepeatMode = VideoPlayActivity.LIST_LOOP;


    private int currentPostiont = 0;
    private int historyTime = 0;

    private SubTitleHelper subTitleHelper;
    private boolean compeleted = false;
    private boolean hasReset = false;
    private boolean copyLibFinished = false;
    private boolean isPlayingAdver = false;

    public MediaHelper() {
        init();
    }

    private void init() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mMediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
                    if (!mUri.toString().endsWith("ISO") && !mUri.toString().endsWith("iso")) {
                        mActivity.progress_Handler.sendEmptyMessage(VideoPlayActivity.SHOW_PROCESS_FLAG);
                    }
                } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
                    mActivity.progress_Handler.sendEmptyMessage(VideoPlayActivity.HIDE_PROCESS_FLAG);
                } else if (what == MediaPlayer.MEDIA_INFO_UNKNOWN) {
                    mActivity.progress_Handler.sendEmptyMessage(VideoPlayActivity.HIDE_PROCESS_FLAG);
                }
                return true;
            }
        });
        mMediaPlayer.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
            @Override
            public void onTimedText(MediaPlayer mp, TimedText text) {
                Message msg = new Message();
                msg.what = VideoPlayActivity.SHOW_INSIDE_SUBTITLE;
                msg.obj = text == null ? "" : text.getText();
                mActivity.subtitleHandler.sendMessage(msg);
            }
        });
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);

    }

    public void setVideoURI(Uri uri, boolean canVR) {
        mUri = uri;
        mIsPrepared = false;
        isPlayingAdver = false;
        mActivity.progress_Handler.sendEmptyMessage(VideoPlayActivity.SHOW_PROCESS_FLAG);
        openVideo();
    }

    public void stopPlayback() {
        if (mMediaPlayer != null) {
            try {
                currentPostiont = mMediaPlayer.getCurrentPosition();
                mMediaPlayer.stop();
                mMediaPlayer.release();
                mMediaPlayer = null;
                mUri = null;
                System.gc();
            } catch (Exception e) {
            }
        }
    }

    public void setshowSubTitleFlag(boolean showSubTitleFlag) {
        subTitleHelper.setshowSubTitleFlag(showSubTitleFlag);
    }

    public void openVideo() {
        if (mUri == null) {
            return;
        }
        mMediaPlayer.setOnErrorListener(null);
        try {
            int need = 0;
            if (mUri.toString().endsWith(".rmvb") || mUri.toString().endsWith(".RMVB") || mUri.toString().endsWith(".rm") || mUri.toString().endsWith(".RM")) {
                need = LibSwitchHelper.RMVB_LIB;
            } else {
                need = LibSwitchHelper.ISO_LIB;
            }
            if (!LibSwitchHelper.checkLib(need)) {
                SystemProperties.set("media.rkffplayer.ready", "false");
                switch (need) {
                    case LibSwitchHelper.RMVB_LIB:
                        SystemProperties.set("media.rkffplayer.mode", "rmvb");
                        break;
                    case LibSwitchHelper.ISO_LIB:
                        SystemProperties.set("media.rkffplayer.mode", "common");
                        break;
                }
                int repeatCount = 0;
                while (true) {
                    if (repeatCount > 60) {
                        mErrorListener.onError(mMediaPlayer, 0, 0);
                        return;
                    }
                    boolean ready = SystemProperties.getBoolean("media.rkffplayer.ready", false);
                    if (!ready) {
                        Thread.sleep(100);
                    } else {
                        break;
                    }
                    repeatCount++;
                    Log.e("fuck you", repeatCount + "sssss");
                }
                copyLibFinished = true;
            }
            if (!mActivity.canPlay()) {
                return;
            }
            mMediaPlayer.reset();
            mDuration = 0;
            mCurrentBufferPercentage = 0;
            mMediaPlayer.setOnPreparedListener(mPreparedListener);
            mMediaPlayer.setOnErrorListener(mErrorListener);
            mMediaPlayer.setOnCompletionListener(mCompletionListener);
            mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
            mMediaPlayer.setLooping(false);
            String path = mUri.toString();
            if (path.contains("/storage/emulated")) {
                if (path.endsWith("ISO") || path.endsWith("iso")) {
                    path = mUri.getPath().replace("/storage/emulated", "/data/media");
                    mMediaPlayer.setDataSource(mActivity, Uri.fromFile(new File(path)));
                } else {
                    File file = new File(mUri.getPath());
                    if (file.exists()) {
                        if (file.isDirectory()) {
                            path = mUri.getPath().replace("/storage/emulated", "/data/media");
                            mMediaPlayer.setDataSource(mActivity, Uri.fromFile(new File(path)));
                        } else {
                            mMediaPlayer.setDataSource(mActivity, mUri);
                        }
                    } else {
                        mErrorListener.onError(mMediaPlayer, 0, 0);
                        return;
                    }
                }
            } else {
                mMediaPlayer.setDataSource(mActivity, mUri);
            }
            mMediaPlayer.prepareAsync();
        } catch (IOException ex) {
            mErrorListener.onError(mMediaPlayer, 0, 0);
            return;
        } catch (IllegalArgumentException ex) {
            mErrorListener.onError(mMediaPlayer, 0, 0);
            return;
        } catch (Exception ex) {
            mErrorListener.onError(mMediaPlayer, 0, 0);
            ex.printStackTrace();
            return;
        }
    }


    MediaPlayer.OnPreparedListener mPreparedListenerReset = new MediaPlayer.OnPreparedListener() {
        public void onPrepared(MediaPlayer mp) {
            compeleted = false;
            hasReset = false;

            prepare();
        }
    };
    MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
        public void onPrepared(MediaPlayer mp) {
            compeleted = false;
            if (hasReset) {
                return;
            }
            prepare();
        }
    };

    private void prepare() {
        mIsPrepared = true;
        mActivity.init3DState();
//        mActivity.send3DMessage();
        mDuration = mMediaPlayer.getDuration();
        seekTo(historyTime);
        mMediaPlayer.start();
        historyTime = 0;
        mActivity.progress_Handler.removeMessages(VideoPlayActivity.SHOW_PROCESS_FLAG);
        mActivity.progress_Handler.sendEmptyMessage(VideoPlayActivity.HIDE_PROCESS_FLAG);
        mActivity.dismissLoading();
        mActivity.hideVideoController();
        subTitleHelper.decodeSub(mUri, mMediaPlayer);
    }

    private MediaPlayer.OnCompletionListener mCompletionListener =
            new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    compeleted = true;
                    try {
                        if (mIsPrepared) {
                            currentPostiont = mMediaPlayer.getDuration();
                        } else {
                            currentPostiont = 0;
                        }
                    } catch (Exception e) {
                        currentPostiont = 0;
                    }
                    if (mActivity.isActivityRunning) {
                        if (adverInterface != null) {
                            adverInterface.onVideoComplete();
                        }
                    }
                }
            };

    private MediaPlayer.OnErrorListener mErrorListener =
            new MediaPlayer.OnErrorListener() {
                public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
                    if (copyLibFinished) {
                        copyLibFinished = false;
                        return true;
                    }
                    if (mMediaPlayer != null) {
                        mMediaPlayer.setScreenOnWhilePlaying(true);
                    }
                    if (mActivity.getwindowtoken() != null) {
                        mActivity.mHandler.sendEmptyMessageDelayed(VideoPlayActivity.MEDIAERROR, 1000);
                    }
                    return true;
                }
            };
    private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener =
            new MediaPlayer.OnBufferingUpdateListener() {
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    mCurrentBufferPercentage = percent;
                }
            };

    public void start() {
        mActivity.acquireWakeLock();
        if (isPlayingAdver) {
            mMediaPlayer.start();
        } else {
            if (mMediaPlayer != null && mIsPrepared) {
                mMediaPlayer.start();
            }
        }
    }

    public void pause() {
        if (isPlayingAdver) {
            mMediaPlayer.pause();
        } else {
            if (mMediaPlayer != null && mIsPrepared) {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                    mActivity.releaseWakeLock();
                    System.gc();
                }
            }
        }
    }

    public void restart() {
        if (mMediaPlayer.isPlaying()) {
            return;
        }
        try {
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                historyTime = mMediaPlayer.getCurrentPosition();
            }
            mIsPrepared = false;
            mDuration = 0;
            mCurrentBufferPercentage = 0;
            hasReset = true;
            reset();
            mMediaPlayer.setOnPreparedListener(mPreparedListenerReset);
            mMediaPlayer.setLooping(false);
            String path = mUri.toString();
            if (path.contains("/storage/emulated")) {
                if (path.endsWith("ISO") || path.endsWith("iso")) {
                    path = mUri.getPath().replace("/storage/emulated", "/data/media");
                    mMediaPlayer.setDataSource(mActivity, Uri.fromFile(new File(path)));
                } else {
                    File file = new File(mUri.getPath());
                    if (file.exists()) {
                        if (file.isDirectory()) {
                            path = mUri.getPath().replace("/storage/emulated", "/data/media");
                            mMediaPlayer.setDataSource(mActivity, Uri.fromFile(new File(path)));
                        } else {
                            mMediaPlayer.setDataSource(mActivity, mUri);
                        }
                    } else {
                        mErrorListener.onError(mMediaPlayer, 0, 0);
                        return;
                    }
                }
            } else {
                mMediaPlayer.setDataSource(mActivity, mUri);
            }
            mMediaPlayer.prepareAsync();
        } catch (Exception e) {
          Log.e("fuck you",e.toString()+"ssss");
        }
    }

    private void reset() {
        mMediaPlayer.reset();
    }

    private MediaPlayer mediaPlayer;

    public void StopPlay() {
        if (mMediaPlayer != null) {
            currentPostiont = mMediaPlayer.getCurrentPosition();
            mediaPlayer = mMediaPlayer;
            mMediaPlayer = null;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mediaPlayer.stop();
                        mediaPlayer.reset();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    } catch (Exception e) {

                    }
                }
            }).start();
        }
        subTitleHelper.finishDecode();
    }

    public int getDuration() {
        return mDuration;
    }

    public int getCurrentPosition() {
        if (isPlayingAdver) {
            return 0;
        }
        if (mMediaPlayer != null && mIsPrepared) {
            try {
                if (compeleted) {
                    return mMediaPlayer.getDuration();
                }
                currentPostiont = mMediaPlayer.getCurrentPosition();
                return currentPostiont;
            } catch (Exception e) {
            }
        }
        return currentPostiont;
    }

    public void seekTo(int msec) {
        if (mMediaPlayer != null && mIsPrepared) {
            try {
                mMediaPlayer.seekTo(msec);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isPlaying() {
        if (mMediaPlayer != null && mIsPrepared) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    public int getBufferPercentage() {
        if (mMediaPlayer != null) {
            return mCurrentBufferPercentage;
        }
        return 0;
    }

    public void setActivity(VideoPlayActivity newactivity, SubTitleHelper subTitleHelper) {
        mActivity = newactivity;
        this.subTitleHelper = subTitleHelper;
    }

    public void Finish() {
        StopPlay();
        mActivity.finish();
    }

    public boolean isPrepare() {
        if (mIsPrepared && mMediaPlayer != null) {
            return true;
        }
        return false;
    }

    public void setHistoryTime(int historyTime) {
        this.historyTime = historyTime;
    }

    public MediaPlayer getmMediaPlayer() {
        return mMediaPlayer;
    }


    public void setAdverURI(Uri uri, int mode) {
        isPlayingAdver = true;
        mUri = uri;
        mIsPrepared = false;
        this.adverMode = mode;
        try {
            if (mode != END){
                historyTime = mMediaPlayer.getCurrentPosition();
            }else{
                historyTime = 0;
            }
            mMediaPlayer.stop();
            mMediaPlayer.reset();
        } catch (Exception e) {

        }
        openAdver();
    }

    public void openAdver() {
        if (mUri == null) {
            return;
        }
        mMediaPlayer.setOnErrorListener(null);
        try {
            if (!mActivity.canPlay()) {
                return;
            }
            mDuration = 0;
            mCurrentBufferPercentage = 0;
            mMediaPlayer.setOnCompletionListener(mAdverCompletionListener);
            mMediaPlayer.setOnPreparedListener(mmAdverPreparedListener);
            mMediaPlayer.setOnErrorListener(mmAdverErrorListener);
            mMediaPlayer.setDataSource(mActivity, mUri);
            mMediaPlayer.prepareAsync();
            if(adverMode==END){
                mMediaPlayer.setLooping(true);
            }
        } catch (IOException ex) {
            mmAdverErrorListener.onError(mMediaPlayer, 0, 0);
            return;
        } catch (IllegalArgumentException ex) {
            mmAdverErrorListener.onError(mMediaPlayer, 0, 0);
            return;
        } catch (Exception ex) {
            mmAdverErrorListener.onError(mMediaPlayer, 0, 0);
            ex.printStackTrace();
            return;
        }
    }

    private MediaPlayer.OnCompletionListener mAdverCompletionListener =
            new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    isPlayingAdver = false;
                    if(adverMode != END){
                        try {
                            mMediaPlayer.stop();
                            mMediaPlayer.reset();
                        } catch (Exception e) {

                        }
                    }
                    if (adverInterface != null) {
                        adverInterface.onAdverComplete();
                    }
                }
            };
    private MediaPlayer.OnErrorListener mmAdverErrorListener =
            new MediaPlayer.OnErrorListener() {
                public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
                    isPlayingAdver = false;
                    try {
                        mMediaPlayer.stop();
                        mMediaPlayer.reset();
                    } catch (Exception e) {

                    }
                    if (adverInterface != null) {
                        adverInterface.onAdverComplete();
                    }
                    return true;
                }
            };
    MediaPlayer.OnPreparedListener mmAdverPreparedListener = new MediaPlayer.OnPreparedListener() {
        public void onPrepared(MediaPlayer mp) {
            if (adverInterface != null) {
                adverInterface.onAdverStart(mMediaPlayer.getDuration() / 1000);
            }
            mMediaPlayer.start();
        }
    };

    public interface AdverInterface {
        void onAdverStart(int duration);

        void onAdverComplete();

        void onVideoComplete();
    }

    public void setAdverInterface(AdverInterface adverInterface) {
        this.adverInterface = adverInterface;
    }

    public boolean getAderPlayingState() {
        return isPlayingAdver;
    }

    public void closeAdver() {
        isPlayingAdver = false;
        try {
            mMediaPlayer.stop();
            mMediaPlayer.reset();
        } catch (Exception e) {

        }
        if (adverInterface != null) {
            adverInterface.onAdverComplete();
        }

    }
}
